package com.caoheng.pay.pay.handler;

import com.alibaba.fastjson.JSONObject;
import com.caoheng.core.common.body.PayRequestBody;
import com.caoheng.core.enums.PayType;
import com.caoheng.core.exceptions.ParamException;
import com.caoheng.pay.pay.channel.PayChannel;
import com.caoheng.pay.pay.channel.wrap.RoutePayChannel;

public class SimplePayExecutor extends BasePayExecutor {

    private PayChannel payChannel;

    private PayType payType;


    public SimplePayExecutor(){

    }
    @Override
    public <E> E doExecute(JSONObject payRequestParam,PayRequestBody body) {
        //1.判断支付的渠道类型
        prepare(body.getPayType());
        //2.根据渠道的类型选择具体的支付渠道
        ensureChannel(body);
        //3.执行支付返回支付结果
        payChannel.executeForPay(payRequestParam);
        //4.后置处理支付结果，例如保存当前支付记录

        //5.消息推送

        return null;
    }

    private void prepare(String payType){
        this.payType = PayType.get(payType);
        if(payType == null){
            throw new ParamException("not valid pay channel for " + payType);
        }
    }

    private void ensureChannel(PayRequestBody requestBody){
        this.payChannel = new RoutePayChannel(payType,requestBody);
    }
}
